package com.example.springboot.controller;

import com.example.springboot.dto.LaundryTipDTO;
import com.example.springboot.entity.LaundryTip;
import com.example.springboot.service.LaundryTipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/laundry-tips")
public class LaundryTipController {

    @Autowired
    private LaundryTipService laundryTipService;

    // 获取所有启用的洗护小知识（无需权限）
    @GetMapping("/active")
    public ResponseEntity<List<LaundryTip>> getActiveLaundryTips() {
        return ResponseEntity.ok(laundryTipService.getActiveLaundryTips());
    }

    // 获取所有洗护小知识（需要超级管理员权限）
    @GetMapping
    public ResponseEntity<List<LaundryTip>> getAllLaundryTips(HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        List<LaundryTip> tips = laundryTipService.getAllLaundryTips(username);
        if (tips == null) {
            return ResponseEntity.status(403).body(null); // 服务层返回 null 表示无权限
        }
        return ResponseEntity.ok(tips);
    }

    // 创建洗护小知识（需要超级管理员权限）
    @PostMapping
    public ResponseEntity<LaundryTip> createLaundryTip(
            @RequestBody LaundryTipDTO dto,
            HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        LaundryTip tip = laundryTipService.createLaundryTip(dto, username);
        if (tip == null) {
            return ResponseEntity.status(403).body(null);
        }
        return ResponseEntity.ok(tip);
    }

    // 更新洗护小知识（需要超级管理员权限）
    @PutMapping("/{tipId}")
    public ResponseEntity<LaundryTip> updateLaundryTip(
            @PathVariable Integer tipId,
            @RequestBody LaundryTipDTO dto,
            HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        LaundryTip tip = laundryTipService.updateLaundryTip(tipId, dto, username);
        if (tip == null) {
            return ResponseEntity.status(403).body(null);
        }
        return ResponseEntity.ok(tip);
    }

    // 删除洗护小知识（需要超级管理员权限）
    @DeleteMapping("/{tipId}")
    public ResponseEntity<Void> deleteLaundryTip(
            @PathVariable Integer tipId,
            HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        boolean success = laundryTipService.deleteLaundryTip(tipId, username);
        if (!success) {
            return ResponseEntity.status(403).build();
        }
        return ResponseEntity.ok().build();
    }
}